<template>
  <div>
    <h2>4----逛水果店</h2>
    <table border="2">
      <tr>
        <td>欢迎光临小熊水果店</td>
      </tr>
      <tr>
        <td v-for="(item, index) in arr" :key="index">
          <p class="goods">
            <span> {{ item.fruit }}</span>
            <span> {{ item.price }}</span> ￥/斤,
            <span>{{ item.discount }}</span> 折优惠
          </p>
        </td>
      </tr>
      <tr>
        <td>你想购买: <input v-model.number="num" type="number" /> 斤</td>
      </tr>
      <tr>
        <td>
          <button @click="buyFn">买单</button>
        </td>
      </tr>
      <tr>
        <td>
          总价：{{ allPrice }} 元 ;折后价：{{ disPrice }} 元' 省了：{{
            (allPrice - disPrice).toFixed(2)
          }}
          元
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  methods: {
    buyFn() {
      if (this.num <= 0) return alert("至少购买1斤水果");
      //折后价
      this.disPrice = this.arr.reduce((sum, item) => {
        return (sum += item.price * this.num * (item.discount / 10)).toFixed(2);
      }, 0);
      //总价
      this.allPrice = this.arr
        .reduce((sum, item) => (sum += item.price * this.num), 0)
        .toFixed(2);
    },
  },
  data() {
    return {
      allPrice: 0,
      disPrice: 0,
      num: 0,
      arr: [{ fruit: "苹果", price: 10, discount: 8 }],
    };
  },
};
</script>

<style>
.goods {
  font-weight: 700;
  margin: 0;
  padding: 0;
}
</style>